import React from 'react';
import {Form, Select, Input, Button, Card, Modal, Popover, Pagination, Message, DatePicker, Icon, Spin } from 'antd';
import FinanceModal from '../../../../components/financeModal/finance';
const FormItem = Form.Item;
const Option = Select.Option;

let RoomLIst = React.createClass({
  contextTypes: {
    router: React.PropTypes.object
  },

  getInitialState() {
    let currentPage = this.props.location.state ? this.props.location.state.currentPage :　1;
    console.log(this.props.location.state)
    return {
      data: [], //列表数据
      formStatus: '',
      dataBox: null,
      financeVisible: false,
      rentContractId: '',
      checkState: { // 卡片选中状态
        allBox: false,
        roomBox: false,
        rentBox: false,
        bookBox: false,
        batcheBox: false,
        emptyBox: false,
        contactExpire:false,
      },
      selected: {
        '1': 'room-icon',
        '2': 'book-icon',
        '3': 'rent-icon',
        '4': 'batche-icon',
        '5': 'contactExpire-icon',
        '-1': 'empty-icon'
      },
      page: { // 分页
        total: 0,
        current: currentPage,
        pageSize: 5
      }
    }
  },
  componentDidMount() {
    this.handleSearch();
  },

  handlePageChange(page) {
    let pager = this.state.page;
    pager.current = page;
    this.setState({
      pagination: {
        current: pager
      }
    })
    this.handleSearch();
  },

  // 获取列表数据
  fetch(status) {
    let forms = this.props.form.getFieldsValue();
    let page = this.state.page.current;
    let keyStatus = status == 'all' ? '' : status;
    let formStatus = {status: status !== undefined ? keyStatus : this.state.formStatus };
    let params = Object.assign({}, {pageSize: 5, currentPage: page}, forms, formStatus);
    let _me = this
    console.log(params);
    Utils.sendAjax({
      url: '/tenement/list',
      data: JSON.stringify(params),
      callback: function(result) {
        if (result.code == '200') {
          _me.setState({
            data: result.data,
            dataBox: _me.renderBox(result.data),
            loading: false,
            page: {
              total: result.page.total,
              pageSize: 5,
              current: result.page.currentPage,
            }
          })
        } else {
          Message.error(result.message, 10);
        }
      }
    })
  },

  //选中状态
  checkStatus(value) {
    let newStr = this.state.checkState;
    console.log(newStr);
    let key = value.status == 'all' ? '' : value.status;
    for (let o in newStr) {
      newStr[o] = false;
    }
    newStr[value.check] = !newStr[value.check];
    let page = this.state.page;
    page.current = 1;
    this.setState({
      checkState: newStr,
      formStatus: key,
      page:page
    })
    this.fetch(value.status);
  },

  setModalVisible(item) {
    console.log(item)
    this.setState({
      financeVisible: true,
      tenementId: item.tenementId,
      rentContractId: item.rentContractId,
    });
  },

  willFinancing(item,its,e) {
    let _me = this;
    console.log(item, its)

    let tenementId = its.tenementId;
    let rentContractId = item.rentContractId;
    Utils.sendAjax({
      url: '/loan/apply/check',
      data: JSON.stringify({tenementId: tenementId,rentContractId: rentContractId,type: 103}),
      callback: (result)=> {
        if(result.code == '200') {
          _me.setModalVisible(item)
        }else{
          Message.error(result.message, 10)
        }
      }
    })

  },

  // 卡片列表渲染模板
  renderBox(data) {

    if (!data[0]) {
      return (
        <li className="none-data">
          <span><Icon type="frown" />暂无数据...</span>
        </li>
      )
    }
    const formItemLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 14 },
    };
    let boxArr = [];
    data.forEach( (item) => {
      let subArr = [];
      let content = (
        <Form horizontal className="form-wrap-li">
          <div>
            <h5>房间信息</h5>
            <FormItem {...formItemLayout}
              label="房间面积">
              <p className="ant-form-text" >{item.area ? item.area : '--'}平方米</p>
            </FormItem>
          </div>
          { item.status !== 99 ?
          <div>
            <h5>房间信息</h5>
            <FormItem {...formItemLayout}
              label="租客姓名">
              <p className="ant-form-text" >{item.renterName}</p>
            </FormItem>
            <FormItem {...formItemLayout}
              label="联系电话">
              <p className="ant-form-text" >{item.phone}</p>
            </FormItem>
            <FormItem {...formItemLayout}
              label="房屋租金">
              <p className="ant-form-text" >{item.contractRent}元/月</p>
            </FormItem>
            <FormItem {...formItemLayout}
              label="合约时间">
              <p className="ant-form-text" >{item.startTime ? item.startTime : '--'}</p>
            </FormItem>
            <FormItem {...formItemLayout}
              label="下次付款日">
              <p className="ant-form-text" >{item.nextRentTime ? item.nextRentTime : '--'}</p>
            </FormItem>
          </div> : null }
          <FormItem >
            {item.status == -1 ? <Button type="ghost" size="small" onClick={this.handleResert.bind(this, item)} disabled>预订</Button> : null}
            {item.status == -1 || item.status == 2 ? <Button type="ghost" size="small" onClick={this.handleSign.bind(this, item)} disabled>签约</Button> : null}
            {item.status == 3 || item.status == 1 || item.status == 4 ? <Button type="ghost" size="small" onClick={this.handleCollect.bind(this, item)} disabled>收租</Button> : null}
            {item.status == 3 || item.status == 1 || item.status == 4 || item.status == 5 ? <Button type="ghost" size="small" onClick={this.handleCheckOutOrderAdd.bind(this, item)} disabled>退租</Button> : null}
            {item.status == 3 || item.status == 1 || item.status == 4 || item.status == 5  ?  <Button type="ghost" size="small" onClick={this.handleHistory.bind(this, item)} disabled>收租历史</Button> : null}
            {(item.status == 4 || item.status == 3 || item.status == 1  ) && item.isConfig == 1 ?  <Button type="ghost" size="small" onClick={this.handleSetsModify.bind(this, item)}>修改配置</Button> : null}
          </FormItem>
        </Form>
      );
      console.log(item.roomList);
      item.roomList.forEach((its)=> {
        its.tenementId = item.tenementId;
        let contentIts = (
          <Form horizontal className="form-wrap-li">
            <div>
              <h5>房间信息</h5>
              <FormItem {...formItemLayout}
                label="房间面积">
                <p className="ant-form-text" >{its.area}平方米</p>
              </FormItem>
            </div>
            {its.status !== -1 ?
            <div>
              <h5>租客信息</h5>
              <FormItem {...formItemLayout}
                label="租客姓名">
                <p className="ant-form-text" >{its.renterName}</p>
              </FormItem>
              <FormItem {...formItemLayout}
                label="联系电话">
                <p className="ant-form-text" >{its.phone}</p>
              </FormItem>
              <FormItem {...formItemLayout}
                label="房屋租金">
                <p className="ant-form-text" >{its.contractRent}元/月</p>
              </FormItem>
              <FormItem {...formItemLayout}
                label="合约时间">
                <p className="ant-form-text" >{its.startTime ? its.startTime : '--'}至{its.endTime ? its.endTime : '--'}</p>
              </FormItem>
              <FormItem {...formItemLayout}
                label="下次付款日">
                <p className="ant-form-text" >{its.nextRentTime ? its.nextRentTime : '--'}</p>
              </FormItem>
            </div> : null}
            <FormItem >
              {its.status == -1 ? <Button type="ghost" size="small" onClick={this.handleResert.bind(this, its)}>预订</Button> : null}
              {its.status == -1 || its.status == 2 ? <Button type="ghost" size="small" onClick={this.handleSign.bind(this, its)}>签约</Button> : null}

              {its.status == 1 || its.status == 3 || its.status == 4 ? <Button type="ghost" size="small" onClick={this.handleCollect.bind(this, its)} >收租</Button> : null}
              {its.status == 1 || its.status == 3 || its.status == 4 || its.status == 5 ? <Button type="ghost" size="small" onClick={this.handleCheckOutOrderAdd.bind(this, its)} >退租</Button> : null}
              {its.status == 1 || its.status == 3 || its.status == 4 || its.status == 5 ?  <Button type="ghost" size="small" onClick={this.handleHistory.bind(this, its)} >收租历史</Button> : null}
              { its.status == 4 || its.status == 3 || its.status == 1  ?  <Button type="ghost" size="small" onClick={this.handleSetsModify.bind(this, its)}>修改配置</Button> : null}
            </FormItem>
          </Form>
        );

        let subLi = (<li className="ul-subroom-li" key={`subli-${its.roomId}`}>
          <Popover placement="right" title="租赁信息" content={contentIts} trigger="click" overlayStyle={{zIndex:100}}>
            <Card >

              <p className="icon-warp">
                <i className={`icon-box  ${this.state.selected[its.status]}`}></i>
                <span style={{marginLeft: 50}}>{its.roomName}室</span>
                {its.isShared == 1 ? <span className="dec-icon-bg">整租</span> : null}
              </p>
              {its.isBorrow === 2 ?
                <div>
                  <p className="icon-margin"><strong>￥{its.contractRent ? its.contractRent.toFixed(2) : (its.rent ? its.rent.toFixed(2) : '0.00')}</strong></p>
                </div>
                :
                <div>
                  <p className="icon-margin"><strong>￥{its.contractRent ? its.contractRent.toFixed(2) : (its.rent ? its.rent.toFixed(2) : '0.00')}</strong>
                    {(its.status == 1 || its.status == 3 || its.status == 4) && its.isBorrow === 1 ? <span className="loanIcon"  >融</span>:''}
                  </p>
                  {/*<p>备注文字：正常出租</p>*/}
                  <p>{(its.status == 1 || its.status == 3 || its.status == 4) && its.isBorrow !== 1 ? <Button className="loanFincail" type="ghost" size="small" onClick={this.willFinancing.bind(this, its, item,{...item.tenementId})} >我要融资</Button> : null}</p>
                </div>
              }

            </Card>
          </Popover>
        </li>)
        subArr.push(subLi);
      })

      let boxDom = (
        <li className="ul-wrapsource-li" key={`li-${item.tenementId}`}>
          <div className="li-title"><h3>{item.tenementName ? item.tenementName : '--'}</h3><span>{item.tenementAddress}</span></div>
          { item.roomList[0] ? <ul>{subArr}</ul> :
            <Popover placement="right" title="租赁信息" content={content} trigger="click" overlayStyle={{zIndex:100}}>
              <Card >
                <p className="icon-warp">
                  <i className="icon-box empty-icon"></i>
                  <span className="icon-margin">整套出租</span>
                </p>
                <p className="icon-margin"><strong>￥{item.contractRent ? item.contractRent : '0.00'}</strong></p>
                {/*<p>备注文字：正常出租</p>*/}
              </Card>
            </Popover>
          }
        </li>
      )
      boxArr.push(boxDom)
    })
    return boxArr;
  },

  // 预定
  handleResert(record) {
    let params = {
      roomId: record.roomId,
      currentPage: this.state.page.current
    };
    let goPathUrl= '/landlord/rentManage/advanceOrder/add';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  // 签约
  handleSign(record) {
    console.log(record);
    let goPathUrl= '/landlord/rentManage/signUpOrder/add';
    this.context.router.push({pathname: goPathUrl, state: {...record}});
  },

  // 收租
  handleCollect(record) {
    let params = record;
    console.log(this.state.page.current)
    params.currentPage = this.state.page.current;
    let goPathUrl= '/landlord/rentManage/rentRooms/collect';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  // 退租/取消合约
  handleCheckOutOrderAdd(record) {
    let params =  record;
    let goPathUrl= '/landlord/rentManage/checkOutList/add';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  // 收租历史
  handleHistory(record) {
    let params = {
      rentContractId: record.rentContractId || 0,
      currentPage: this.state.page.current
    };
    let goPathUrl= '/landlord/rentManage/rentRooms/history';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },


  // 修改配置
  handleSetsModify(record) {
    let params = record;
    params.currentPage = this.state.page.current;
    let goPathUrl= '/landlord/rentManage/rentRooms/roomSetsUpdate';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  handleSearch() {
    this.fetch();
  },

 //重置查询栏
  handleReset() {
    this.props.form.resetFields();
  },

  handleCancel() {
    this.setState({
      visible: false,
      financeVisible: false,
    });
  },

  render() {
    const { getFieldProps } = this.props.form;

    const financeChild = {
      financeVisible: this.state.financeVisible,
      tenementId: this.state.tenementId,
      rentContractId: this.state.rentContractId,
      financeType: '103', // 租约贷
      callBack: this.handleCancel,
    };

    return (
      <div>
        <div className="search-bar">
          <Form inline >
            <div className="ant-form-item">
              <label htmlFor="renterName">租客姓名</label>
              <Input {...getFieldProps('renterName') } placeholder="租客姓名" />
              <label htmlFor="mobilePhone" style={{marginLeft: 10}}>联系电话</label>
              <Input {...getFieldProps('mobilePhone')} placeholder="联系电话"/>
              <label htmlFor="renterName" style={{marginLeft: 10}}>房间名</label>
              <Input {...getFieldProps('roomName') } placeholder="房间名" />
         
            </div>
            <div className="ant-form-item">
              <label htmlFor="">合约时间</label>
              <DatePicker  {...getFieldProps('startTimeFirst')} placeholder="合约开始时间起始" />&nbsp;~&nbsp;
              <DatePicker  {...getFieldProps('startTimeSecond')} placeholder="合约开始时间结束" />
              &nbsp;至&nbsp;
              <DatePicker  {...getFieldProps('endTimeFirst')} placeholder="合约结束时间起始" />&nbsp;~&nbsp;
              <DatePicker  {...getFieldProps('endTimeSecond')} placeholder="合约结束时间结束" />
              <label htmlFor="tenementName" style={{marginLeft: 10}}>物业名称</label>
              <Input {...getFieldProps('tenementName') } placeholder="物业名称" />
            </div>

            <FormItem>
              <Button type="primary" onClick={this.handleSearch} style={{marginRight: 20}}>查询</Button>
              <Button type="default" onClick={this.handleReset} >重置</Button>
            </FormItem>
          </Form>
        </div>

        <div>
          <label className={`check-box  ${this.state.checkState.allBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'allBox', status: 'all'})}>
            <i className="icon-box all-icon"></i>
            <span className="icon-margin status-text">全部房间</span>
            <p className="icon-margin"></p>
            {this.state.checkState.allBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>

          <label className={`check-box  ${this.state.checkState.roomBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'roomBox', status: 1})}>
            <i className="icon-box room-icon"></i>
            <span className="icon-margin status-text">正常出租</span>
            <p className="icon-margin"></p>
            {this.state.checkState.roomBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>

          <label className={`check-box  ${this.state.checkState.rentBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'rentBox', status: 3})}>
            <i className="icon-box rent-icon"></i>
            <span className="icon-margin status-text">收租提醒</span>
            <p className="icon-margin"></p>
            {this.state.checkState.rentBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>

          <label className={`check-box  ${this.state.checkState.bookBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'bookBox', status: 2})}>
            <i className="icon-box book-icon"></i>
            <span className="icon-margin status-text">已预订</span>
            <p className="icon-margin"></p>
            {this.state.checkState.bookBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>

          <label className={`check-box  ${this.state.checkState.batcheBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'batcheBox', status: 4})}>
            <i className="icon-box batche-icon"></i>
            <span className="icon-margin status-text">租客欠款</span>
            <p className="icon-margin"></p>
            {this.state.checkState.batcheBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>
          
          <label className={`check-box  ${this.state.checkState.contactExpire ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'contactExpire', status: 5})}>
            <i className="icon-box contactExpire-icon"></i>
            <span className="icon-margin status-text">合约到期</span>
            <p className="icon-margin"></p>
            {this.state.checkState.contactExpire ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>

          <label className={`check-box  ${this.state.checkState.emptyBox ? 'label-checked' : ''}`}
                 onClick={this.checkStatus.bind(this, {check: 'emptyBox', status: -1})}>
            <i className="icon-box empty-icon"></i>
            <span className="icon-margin status-text">空置房屋</span>
            <p className="icon-margin"></p>
            {this.state.checkState.emptyBox ? <span className="icon-triangle blue" ><Icon className="yes" type="check" /></span> : null}
          </label>


        </div>
        <Spin tip="正在加载数据..." spinning={this.state.loading}>
          <ul className="ul-show-card">
            {this.state.dataBox}
          </ul>
        </Spin>
        {this.state.data[0] ?
        <div className="box-page">
          <Pagination onChange={this.handlePageChange}
                      current={this.state.page.current}
                      total={this.state.page.total}
                      pageSize={this.state.page.pageSize} />
        </div>: null}
        <FinanceModal {...financeChild} />
      </div>
    );
  }
});
RoomLIst = Form.create()(RoomLIst);
export default RoomLIst